package com.hhsj.design.pullableview;

import android.view.View;
import android.view.animation.Interpolator;

import androidx.annotation.NonNull;

//从可刷新状态到刷新状态
public abstract class HeaderGoingToRefreshRunnable implements Runnable {

    private View mRefreshViewParent;
    private int mDuration;
    private boolean mIsFinish;//是否完成了从可刷新状态到开始刷新状态的过渡
    private long mStartTime;
    private int targetHeight;//目标位置，这里的目标位置是 原始高度

    private Interpolator mInterpolator = input -> (float) Math.pow(input, 1);

    /**
     * @param targetHeight 布局的目标高度
     */
    public HeaderGoingToRefreshRunnable(@NonNull View refreshViewParent, int targetHeight) {
        this.mRefreshViewParent = refreshViewParent;
        this.mIsFinish = true;
        this.targetHeight = targetHeight;
    }

    public void start(int duration) {
        this.mDuration = duration;
        mRefreshViewParent.removeCallbacks(this);
        if (mIsFinish) {
            mStartTime = System.currentTimeMillis();
            mIsFinish = false;
            mRefreshViewParent.post(this);
            onToRefresh();
        }
    }

    public void cancel() {
        this.mIsFinish = true;
    }

    @Override
    public void run() {
        if (!mIsFinish) {
            long delta = System.currentTimeMillis() - mStartTime;
            if (delta > mDuration) {
                delta = mDuration;
            }
            //当前的视图高度 = 距父布局的高度 + 自身高度
            int currentHeight = mRefreshViewParent.getMeasuredHeight();
            //插值器的值
            final float param = mInterpolator.getInterpolation((mDuration - delta) / (float) mDuration);
            int movedHeight = targetHeight + (int) ((currentHeight - targetHeight) * param);
            if (movedHeight <= targetHeight) {
                updateLayoutHeight(targetHeight);
                mIsFinish = true;
                doRefresh();//标记正在刷新mIsRefresh = true;
            } else {
                updateLayoutHeight(movedHeight);
                mRefreshViewParent.post(this);
            }
        }
    }

    /**
     * 更新布局高度
     *
     * @param movedHeight
     */
    public abstract void updateLayoutHeight(int movedHeight);

    /**
     * 开始刷新，可以操作相关的
     */
    public abstract void doRefresh();

    /**
     * 松手去刷新
     */
    public abstract void onToRefresh();

}
